<template>
  <div class="service-matter-wrapper">
    <p class="title">综合查询</p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="事项名称">
          <el-input v-model="formInline.itemNameLike" placeholder="请输入事项名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="事项类型">
          <el-select v-model="formInline.itemType" placeholder="请选择事项类型">
            <el-option
              v-for="(item) in itemTypeOpts"
              :key="item.dictoryValue"
              :label="item.dictoryName"
              :value="item.dictoryValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增事项</el-button>
        <!-- <el-button size="medium" @click="exportTable">导出</el-button> -->
        <!-- <el-button size="medium" @click="batchDeletion">批量删除</el-button> -->
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table ref="multipleTable" v-loading="loading" :data="tableData" stripe @selection-change="selectionChange">
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + startNum + 1 }}</template>
        </el-table-column>
        <el-table-column label="事项名称" prop="itemName"></el-table-column>
        <el-table-column label="事项编码" prop="itemCode"></el-table-column>
        <el-table-column label="事项类型" prop="itemType">
          <template slot-scope="scope">{{convertKeyToVal(scope.row.itemType, itemTypeOpts)}}</template>
        </el-table-column>
        <el-table-column label="资金来源" prop="fundingSource"></el-table-column>
        <el-table-column label="服务时限" prop="serviceTime"></el-table-column>
        <el-table-column label="操作" min-width="120">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.itemId)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.itemId)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.itemId)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        layout="total, prev, pager, next"
        :total="totalCount"
        @current-change="pageChange">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="服务事项" :visible.sync="dialogFormVisible" width="80vw" @closed="closeDialog" :close-on-click-modal="false">
      <el-form ref="ruleDialog" :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" label-width="134px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="事项名称" prop="itemName">
              <el-input v-model="dialogForm.itemName" placeholder="请输入事项名称" autocomplete="off" maxlength="250"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事项编码" prop="itemCode">
              <el-input v-model="dialogForm.itemCode" placeholder="请输入事项编码" autocomplete="off" maxlength="250"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="事项类型" prop="itemType">
              <el-select v-model="dialogForm.itemType" placeholder="请选择事项类型">
                <el-option
                  v-for="(item) in itemTypeOpts"
                  :key="item.dictoryValue"
                  :label="item.dictoryName"
                  :value="item.dictoryValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资金来源" prop="fundingSource">
              <el-input v-model="dialogForm.fundingSource" placeholder="请输入资金来源" autocomplete="off" maxlength="250"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务时限" prop="serviceTime">
              <el-input v-model="dialogForm.serviceTime" placeholder="请输入服务时限" autocomplete="off" maxlength="250"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构要求" prop="institutionalRequirements">
              <el-input v-model="dialogForm.institutionalRequirements" placeholder="请输入机构要求" autocomplete="off" maxlength="250"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审批部门" prop="approvalDepartment">
          <el-input v-model="dialogForm.approvalDepartment" placeholder="请输入审批部门" autocomplete="off" maxlength="250"></el-input>
        </el-form-item>
        <el-form-item label="设置依据" prop="foundation">
          <div v-show="dialogMode===CNST.READ_MODE" v-html="dialogForm.foundation" class="read-text"></div>
          <tinymce ref="matterTiny" v-show="dialogMode!==CNST.READ_MODE" v-model="dialogForm.foundation" :height="350"></tinymce>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="dialogMode!==CNST.READ_MODE" @click="submitOrg">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import {
  getServiceItemList,
  getServiceItemDetail,
  addServiceItem,
  updateServiceItem,
  deleteServiceItem
} from '@/api/agencyService'
import {
  getDictionaryDataByCode
} from '@/api/systemManage'
import { deepClone } from '@/utils'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'ServiceMatter',
  data() {
    return {
      itemTypeOpts: [],
      formInline: {
        itemNameLike: '',
        itemType: ''
      },
      loading: false,
      tableData: [],
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      totalCount: 0, // 总共多少条
      currentPage: 1, // 分页当前页
      dialogFormVisible: false,
      dialogForm: {
        itemName: '',
        itemCode: '',
        itemType: '',
        fundingSource: '',
        serviceTime: '',
        institutionalRequirements: '',
        approvalDepartment: '',
        foundation: ''
      },
      rules: {
        itemName: [{ required: true, message: '请输入事项名称', trigger: 'blur' }],
        itemCode: [{ required: true, message: '请输入事项编码', trigger: 'blur' }],
        itemType: [{ required: true, message: '请输入事项类型', trigger: 'blur' }],
        fundingSource: [{ required: true, message: '请输入资金来源', trigger: 'blur' }],
        serviceTime: [{ required: true, message: '请输入服务时限', trigger: 'blur' }],
        institutionalRequirements: [{ required: true, message: '请输入机构要求', trigger: 'blur' }],
        approvalDepartment: [{ required: true, message: '请输入审批部门', trigger: 'blur' }]
      },
      startNum: 0
    }
  },
  components: {
    Tinymce
  },
  methods: {
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.dictoryValue === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].dictoryName
    },
    async getOrgListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          itemNameLike: this.formInline.itemNameLike.trim(),
          itemType: this.formInline.itemType,
        }
        var res = await getServiceItemList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    searchOrg() {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    resetSearch() {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    popNewAddDialog() {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    selectionChange() {},
    pageChange (curPage) {
      this.currentPage = curPage
      this.startNum = (curPage - 1) * 10
      this.getOrgListAndShow()
    },
    showToDialog (res) {
      let data = res.data
      let foundation = data.foundation
      if (foundation) {
        let newfoundation = foundation.replace(/src="\//g, `src="${res.fileUrlPrefix}/`)
        data.foundation = newfoundation
      }
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
      this.$refs.matterTiny.setContent(this.dialogForm.foundation)
    },
    viewDetail(itemId) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getServiceItemDetail({ itemId }).then((res) => {
        this.showToDialog(res)
      })
    },
    editDetail (itemId) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = itemId
      getServiceItemDetail({ itemId }).then((res) => {
        this.showToDialog(res)
      })
    },
    deleteDetail(itemId) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteServiceItem({ itemId }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    closeDialog() {
      this.$refs.matterTiny.setContent('')
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.$set(this.dialogForm, key, '')
      }
    },
    submitOrg() {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          let userPm = JSON.parse(localStorage.getItem('user_pm'))
          var patt=new RegExp(userPm.fileUrlPrefix, 'g')
          if (requestData.foundation) {
            let newfoundation = requestData.foundation.replace(patt, '')
            newfoundation = newfoundation.replace(/src="..\//g, 'src="/')
            requestData.foundation = newfoundation
          }
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            addServiceItem(requestData).then((res) => {
              this.$message({
                message: '新增服务事项成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.itemId = this.curId
            updateServiceItem(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    }
  },
  mounted() {
    this.getOrgListAndShow()
    getDictionaryDataByCode('ITEM_TYPE').then((res) => {
      this.itemTypeOpts = res.data.queryResult
    })
  }
}
</script>

<style lang="scss" scoped>
.service-matter-wrapper {
  background-color: #ffffff;
  margin-top: 12px;
  border-radius: 4px;
  box-shadow: 0px 0px 22px -2px #d2d6da;
  padding: 20px;
  min-height: calc(100vh - 125px);
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select {
        width: 100%;
      }
      .read-text {
        background-color: #f5f7fa;
        padding: 10px;
        overflow: auto;
        border: 1px solid #eeeeee;
      }
    }
  }
}
</style>
